from sql_operation import MySqlOperation
import json


class OrderList:
    def __init__(self, conn=None, stu_id=None, teacher_id=None, order_time=None):
        self.conn = conn
        # self.sid = stu_id
        # self.tid = teacher_id
        # self.otm = order_time
        self.cur = MySqlOperation()

    def order_list_info(self):
        # 发挥课程信息
        class_info_key = ['class_id', 'teacher_id', 'teacher_name',
                          'class_name', 'class_type', 'class_info', 'class_time']
        class_info_dict = {}
        class_info_list = []
        class_info_sql = "" \
                         "select " \
                         "info.class_id, ti.teacher_id, ti.teacher_name, " \
                         "info.class_name, info.class_type, info.class_info, info.class_time " \
                         "from class_info as info " \
                         "left join teacher_info as ti " \
                         "on ti.teacher_id = info.teacher_id;"

        self.cur.operation(class_info_sql)
        # 返回数据的结构
        # 课程id, 学生id, 教师id, 课程名称, 课程信息, 上课时间,
        class_info_result = self.cur.fetch_all()
        print(class_info_result)

        for class_info in class_info_result:
            for i in range(len(class_info_key)):
                    class_info_dict[class_info_key[i]] = class_info[i]

            class_info_list.append(class_info_dict)

        class_info_response_json = json.dumps(class_info_list)
        print(class_info_response_json)
        self.conn.send(class_info_response_json.encode())

    def teacher_class_info(self, teacher_id):
        # 获得老师开课信息
        teacher_class_info_sql = 'select class_id, class_name, class_type, class_info,teacher_id, class_time, class_status ' \
                                 'from class_info where teacher_id = %s' % teacher_id

        self.cur.operation(teacher_class_info_sql)
        sqlr = self.cur.fetch_all()
        print(sqlr)
        teacher_class_info_key = ['class_id', 'class_name', 'class_type', 'class_info','teacher_id', 'class_time',
                                  'class_status']

        t_class_info_list = []

        for class_info in sqlr:
            t_class_info_dict = {}
            for index in range(len(teacher_class_info_key)):
                t_class_info_dict[teacher_class_info_key[index]] = class_info[index]
            t_class_info_list.append(t_class_info_dict)

        # 打包发送
        t_class_info_json = json.dumps(t_class_info_list)
        print(t_class_info_list)
        self.conn.send(t_class_info_json.encode())

    # 学生接口
    def order_list_add(self, stu_id, class_id):
        is_order_sql = 'select distinct stu_id from order_class_info where stu_id="%s" ' % stu_id

        self.cur.operation(is_order_sql)
        is_ordered = self.cur.fetch_all()

        if is_ordered:
            print('403:已经预约过了，无需重复预约')
            self.conn.send('403:已经预约过了，无需重复预约'.encode())

        elif not is_ordered:
            order_add_sql = 'insert into order_class_info(class_id, stu_id) values(%s, %s)' \
                            % (class_id, stu_id)
            try:
                self.cur.operation(order_add_sql)

            except Exception as e:
                print('课程预约失败, 错误原因：%s' % e)
                self.conn.send('500:课程预约失败，请稍后尝试'.encode())
                self.cur.rollback()

            else:
                print('200:预约成功!')
                self.cur.commit()
                self.conn.send('200:预约成功!'.encode())

            finally:
                self.cur.close_all()

        else:
            print('sql查询结果异常，请检查语句')
            self.conn.send('500:课程预约失败, 请稍后尝试'.encode())

    # 教师接口
    def class_add(self, class_name, class_info, class_type, class_date, class_time, teacher_id, *, class_status=1):
        print('课程预约成功')
        is_have = self.is_have_class(class_time=class_time, class_date=class_date, user_id=teacher_id)
        if not is_have:
            class_add_sql = 'insert into ' \
                            'class_info(class_name, class_type, class_info, teacher_id, ' \
                            'class_date, class_time, class_status) ' \
                            'values(\'%s\', \'%s\', \'%s\', %s, %s, %s, %s);' \
                            % (class_name, class_type, class_info, teacher_id,
                               class_date, class_time, class_status)
            print(class_add_sql)
            try:
                self.cur.operation(class_add_sql)
            except Exception as e:
                self.conn.send('500:课程创建失败,请稍后尝试'.encode())
                print('课程添加失败,错误原因:', e)
                self.cur.rollback()
            else:
                self.conn.send('200:课程创建成功！'.encode())
                self.cur.commit()
        elif is_have:
            print(is_have)
            self.conn.send('403:%s')

    def is_have_class(self, class_date, class_time, user_id, user_type='student'):
        if user_type == 'student':
            pass

        else:
            is_have_sql = 'select class_name from class_info ' \
                          'where teacher_id=%s and class_date=%s and class_time=%s' \
                          % (user_id, class_date, class_time)
            try:
                self.cur.operation(is_have_sql)
            except Exception as e:
                print('查询失败, 错误原因', e)
                return '查询失败, 请稍后尝试'
            else:
                sqlr = self.cur.fetch_all()
                if sqlr:
                    return '该时段是已经预约课程,请确认后再次预约'
                else:
                    return 0

    def order_list_get(self, stu_id):
        # 课程id, 课程名称, 课程简介, 上课时间, 上课类型, 教师名称
        stu_order_key = ['class_name', 'class_type', 'class_info', 'class_time', 'teacher_name']
        stu_order_dict = {}
        get_order_list_sql = 'select c_info.class_name, c_info.class_type, c_info.class_info, ' \
                             'c_info.class_time, th.teacher_name ' \
                             'from class_info as c_info left join order_class_info as oci ' \
                             'on c_info.class_id = oci.class_id and oci.stu_id = %s ' \
                             'left join teacher_info th on th.teacher_id = c_info.teacher_id;' % stu_id

        try:
            self.cur.operation(get_order_list_sql)

        except Exception as e:
            print('学生id:%s 的用户信息查询失败, 错误信息: %s' % (stu_id, e))
            err_msg = '500:学生查询信息失败, 请稍后尝试'
            self.conn.send(err_msg.encode())

        else:
            stu_order_info = self.cur.fetch_all()
            print(stu_order_info)
            stu_class_list = []

            for info in stu_order_info:
                for info_index in range(len(info)):
                    stu_order_dict[stu_order_key[info_index]] = info[info_index]

                stu_class_list.append(stu_order_dict)

            order_info_json = json.dumps(stu_class_list)
            print(order_info_json)
            self.conn.send(('200;' + order_info_json).encode())

    def class_order_count(self, class_id):
        get_order_count_sql = 'select count(stu_id) from order_class_info where class_id = %s group by class_id;' \
                              % class_id
        try:
            self.cur.operation(get_order_count_sql)

        except Exception as e:
            print(e)
            self.conn.send('500:查询失败, 请稍后尝试'.encode())
        else:
            sqlr = self.cur.fetch_all()
            print(sqlr if sqlr else '0')
            self.conn.send(('200:%s' % (sqlr[0][0] if sqlr else '0')).encode())

    def order_cancel(self):
        pass

    def class_cancel(self, teacher_id, class_id):
        class_cancel_sql = 'update class_info set class_status=0 where class_id=%s and teacher_id=%s'\
                           % (class_id, teacher_id)
        print(class_cancel_sql)
        try:
            self.cur.operation(class_cancel_sql)

        except Exception as e:
            print('课程取消失败, 错误原因:', e)
            self.conn.send('500:课程取消失败,请稍后尝试'.encode())
            self.cur.rollback()

        else:
            self.conn.send('200:课程取消成功'.encode())
            self.cur.commit()


if __name__ == '__main__':
    o = OrderList()
    r = o.is_have_class(class_time=10, user_id=1, user_type='teacher')
    print(r)